package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threablocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.校验参数  authorApUserId 必须登录 operation 0 1
        if (dto.getAuthorApUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "对应的用户id不存在");
        }
        Short operation = dto.getOperation();
        if (operation == null || (operation.intValue() != 0 && operation.intValue() != 1)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "关注类型错误");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer id = user.getId();
        Integer followId = dto.getAuthorApUserId();
        //校验之前有没有关注过
        Double score = redisTemplate.opsForZSet()
                .score(UserRelationConstants.FANS_LIST + id, String.valueOf(followId));
        if (operation.intValue() == 0 && score != null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"您已关注，请勿重复操作");
        }
        try {
            //开启 redis 事务
            redisTemplate.multi();
            //2.判断operation 状态
            if (operation.intValue() == 0) {
                //  operation 为 0  没有关注过
                redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + id, String.valueOf(followId), System.currentTimeMillis());
                redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + followId, String.valueOf(id), System.currentTimeMillis());
            } else {
                // operation  为1   取消关注
                redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + id,String.valueOf(followId));
                redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + followId, String.valueOf(id));
            }
            redisTemplate.exec();
        } catch (Exception e) {
            e.printStackTrace();
            // 如果有异常   取消事务
            redisTemplate.discard();
            throw e;
        }
        return ResponseResult.okResult();
    }
}
